from fastapi import FastAPI,Depends, Request,APIRouter
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os
from dotenv import load_dotenv
from contextlib import asynccontextmanager
from fastapi import FastAPI
from typing import AsyncGenerator
from scorpio.routers import base_api_router, chat_api_router, init_api_router, auth_api_router
from scorpio.core.common import setup_logging, get_logger, get_config, close_config
from scorpio.api.rag import document_router, query_router
from scorpio.api import db_router 
from scorpio.core.database import VectorDatabaseManager
from scorpio.services.database import DatabaseInitializerService

load_dotenv()

# 初始化日志配置
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
LOG_DIR: str = os.getenv("LOG_DIR", "logs")
setup_logging(
    log_level=LOG_LEVEL,
    log_dir=LOG_DIR
)

# 获取主应用日志记录器
logger = get_logger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    应用生命周期管理器
    
    替代废弃的 on_event("startup") 和 on_event("shutdown")
    """
    # 应用启动时初始化配置
    # If config file not found, raise error and get none
    logger.info("Starting application scorpio...")
    
    config = get_config()
    app.state.config = config
    logger.info("Start to connect database with VectorDatabaseManager...")
    db_manager = VectorDatabaseManager(config.database)
    await db_manager.initialize()
    app.state.db_manager = db_manager

    logger.info("Start to initialize database...")
    db_initializer = DatabaseInitializerService(db_manager, embedding_config=config.embedding)    
    await db_initializer.initialize()
    app.state.db_initializer = db_initializer

    logger.info(f"✅ Application is running | configuration loaded.")
    
    yield  # 应用运行期间
    
    # 应用关闭时清理资源
    close_config()
    logger.info("🛑 Application shutdown | Clean up resources completed")

app = FastAPI(
    title="Scorpio AI",
    lifespan= lifespan
)

"""
- 后端FastAPI配置了 allow_origins=["*"] （允许所有来源）
- 同时设置了 allow_credentials=True （允许携带凭证）
- 当请求使用 credentials mode: 'include' 时，浏览器不允许通配符*与credentials同时使用
"""
# 配置CORS（保持原有逻辑）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173","http://127.0.0.1:5173"] , # 生产环境域名
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],   # 明确允许的头部
 
    allow_credentials=True,
)

# 注册路由
app.include_router(base_api_router)

chat_api_router.dependencies=[Depends(get_config)] 
app.include_router(chat_api_router)

# 新增：包含初始化会话的路由
app.include_router(init_api_router)
app.include_router(auth_api_router)

app.include_router(document_router)
app.include_router(query_router)
app.include_router(db_router)

@app.get("/ping")
async def ping():
    """轻量级存活检查"""
    return {"status": "ok"}

# 挂载静态文件（使用参数控制路径）
if os.path.isfile("./ui/index.html"):
    app.mount("/", StaticFiles(directory="./ui", html=True), name="static")
else:
    pass

def main():
    import argparse
    import uvicorn

    parser = argparse.ArgumentParser("scorpio")
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=8000)
    args = parser.parse_args()
    uvicorn.run(app, host=args.host, port=args.port)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(
        "scorpio.main:app", 
        port=8010, 
        reload=True)
